package com.Pan.util;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

public class HttpConnectionUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpConnectionUtils.class);

    final static int BUFFER_SIZE = 4096;

    public static String get(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String str = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("Authorization", "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiZ2F0ZXdheS1zZXJ2aWNlIiwiYXV0aC1jZW50ZXIiXSwiYXV0aF90eXBlIjoiIiwidXNlcl90eXBlIjoiMDAiLCJjb21wYW55X2lkIjoiMjAyMjAzMTExMzU0MDQyOTAxMjAxOTQwNDk5NzQyNzIiLCJ1c2VyX2lkIjoiMjAyMjAzMTExNzEwMDYyOTAxNjk1MjgyMTY5ODU2MDAiLCJ1c2VyX25hbWUiOiJnb2xkIiwibmlja19uYW1lIjoi6a2U54iqMuWPtyIsInNjb3BlIjpbInJlYWQiLCJ3cml0ZSJdLCJleHAiOjE2NTE4MDk3MjYsImF1dGhvcml0aWVzIjpbbnVsbCwiIiwiZGNzOnZpc2l0OnBhZ2UiLCJkY3M6Y29sbGVjdDpjb2xsZWN0UXVlc3Rpb246bGlzdCIsImRjczpjb2xsZWN0OmNvbGxlY3RUYXNrOmRlbGV0ZSIsIm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czpwcm9qZWN0OmdldFByb2plY3RMaXN0IiwiZGNzOmRpY3Q6ZGVsZXRlRGljdCIsImRjczp2aXNpdDpnZXRTdG9yZUluZm8iXSwianRpIjoiNDA3MWRiZTctMjA2Mi00YjA4LTgzNDYtNWI3ZmMwODAyNjM5IiwiY2xpZW50X2lkIjoiZ2F0ZXdheS1zZXJ2aWNlIn0.NXs9W_O0uOtqFSVyge15v2DStEU2F6TuAEnabjqX3T6igNtIMfKv38hRMznIL2DE7UcOqdkTpkI6pXak-f_Z5kcATaeTZR82ld37sXgM2Xk838G2yfTVlND_z5lqVKQdfsK3TqopQMXrQIdW78ZureKHNXn5XEZujv7wlO2fDU7aWxFk6Ay8hneHtqzkr4uMQ6oeehWKLNYwouVyismZg5Ts-6cuHPP3WtSuXZx3rosj1JducuefdPTx0jfWbYOqHofurmCs3jr4yFUqzJL1zr6xqERmB3CEUBTyeoYYtaFG_aDcHU-6_BaL9dSyHcpQWFW0qI1pWoEE0fYSRV7duA");
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            logger.info("url = " + url);
            logger.info("http response code = " + response1.getStatusLine().getStatusCode());
            HttpEntity entity1 = response1.getEntity();
            str = HttpConnectionUtils.inputStreamTOString(entity1.getContent());
            logger.info("result = " + str);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static InputStream getStream(String url) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        InputStream in = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            logger.info("url = " + url);
            logger.info("http response code = " + response1.getStatusLine().getStatusCode());
            HttpEntity entity1 = response1.getEntity();
            in = entity1.getContent();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return in;
    }

    public static String get(String url, Map<String, String> header) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String str = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            for (String key : header.keySet()) {
                httpGet.addHeader(key, header.get(key));
            }
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            logger.info("url = " + url);
            logger.info("http response code = " + response1.getStatusLine().getStatusCode());
            HttpEntity entity1 = response1.getEntity();
            str = HttpConnectionUtils.inputStreamTOString(entity1.getContent());
            logger.info("result = " + str);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;

    }

    public static String get(String url, Map<String, String> header, Map<String, String> params) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String str = null;
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (params != null) {
                // 添加请求参数
                for (String key : params.keySet()) {
                    uriBuilder.addParameter(key, params.get(key));
                }
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            if (header != null) {
                for (String key : header.keySet()) {
                    httpGet.addHeader(key, header.get(key));
                }
            }
            CloseableHttpResponse response1 = httpclient.execute(httpGet);
            logger.info("url = " + url);
            logger.info("param:"+ JSON.toJSONString(params));
            logger.info("http response code = " + response1.getStatusLine().getStatusCode());
            HttpEntity entity1 = response1.getEntity();
            str = HttpConnectionUtils.inputStreamTOString(entity1.getContent());
            logger.info("result = " + str);
        } catch (ClientProtocolException e) {
            logger.error("远程调用失败, url:{}, param:{}, exception:" ,url, JSON.toJSONString(params), e);
            e.printStackTrace();
        } catch (IOException e) {
            logger.error("远程调用失败, url:{}, param:{}, exception:" ,url, JSON.toJSONString(params), e);
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            logger.error("远程调用失败, url:{}, param:{}, exception:" ,url, JSON.toJSONString(params), e);
            e.printStackTrace();
        } catch (Exception e) {
            logger.error("远程调用失败, url:{}, param:{}, exception:" ,url, JSON.toJSONString(params), e);
            e.printStackTrace();
        }
        return str;

    }

    private static String inputStreamTOString(InputStream in) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count = -1;
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
            outStream.write(data, 0, count);
        }
        data = null;
        return new String(outStream.toByteArray(), "UTF-8");
    }

    public static String post(String url, String json) {
        CloseableHttpClient client = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(120000).setConnectionRequestTimeout(120000)
                .setSocketTimeout(120000).build();
        CloseableHttpResponse response = null;
        StringEntity entity = null;
        try {
            //建立Request的对象，一般用目标url来构造，Request一般配置addHeader、setEntity、setConfig
            HttpPost req = new HttpPost(url);
            req.setConfig(requestConfig);
            req.addHeader("Content-Type", "application/json;charset=utf-8");
            req.addHeader("apiKey", "apikey-sfa");
            entity = new StringEntity(json, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            req.setEntity(entity);
            logger.info("url = " + url);
//            logger.info("json = " + json);
            long start = System.currentTimeMillis();
            response = client.execute(req);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("http response code = " + response.getStatusLine().getStatusCode());
            logger.info("result = " + result);
//            logger.info("time = " + (System.currentTimeMillis() - start) / 1000.0);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return result;
            }
        } catch (Exception e) {
            logger.error("post http error!", e);
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (Exception e) {
                logger.error("post http error!", e);
            }
        }
        return null;
    }

    public static String post(String url, Object param) {
        String data = JsonUtil.toJsonString(param);
        CloseableHttpClient client = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(120000).setConnectionRequestTimeout(120000)
                .setSocketTimeout(120000).build();
        CloseableHttpResponse response = null;
        StringEntity entity = null;
        try {
            HttpPost req = new HttpPost(url);
            req.setConfig(requestConfig);
            req.addHeader("Accept", "application/json");
            req.addHeader("Content-Encoding", "UTF-8");
            req.addHeader("Content-Type", "application/json; charset=UTF-8");
            entity = new StringEntity(data, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            req.setEntity(entity);
            response = client.execute(req);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("http response code = " + response.getStatusLine().getStatusCode());
            logger.info("result = " + result);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return result;
            }
        } catch (Exception e) {
            logger.error("post http error!", e);
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (Exception e) {
                logger.error("post http error!", e);
            }
         }
        return null;
    }

    /*private String postForFile(String url, MultipartFile multipartFile) {
        CloseableHttpClient client = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(120000).setConnectionRequestTimeout(120000)
                .setSocketTimeout(120000).build();
        CloseableHttpResponse response = null;
        UrlEncodedFormEntity entity = null;
        try {
            //建立Request的对象，一般用目标url来构造，Request一般配置addHeader、setEntity、setConfig
            HttpPost req = new HttpPost(url);
            req.setConfig(requestConfig);
            req.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            List<NameValuePair> nameValuePairArrayList = new ArrayList<NameValuePair>();
                nameValuePairArrayList.add(new BasicNameValuePair("file", multipartFile));
            entity = new UrlEncodedFormEntity(nameValuePairArrayList, "utf-8");
            req.setEntity(entity);
            logger.info("url = " + url);
            response = client.execute(req);
            String result = EntityUtils.toString(response.getEntity(), "UTF-8");
            logger.info("http response code = " + response.getStatusLine().getStatusCode());
            logger.info("result = " + result);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                return result;
            }
        } catch (Exception e) {
            logger.error("post http error!", e);
        } finally {
            try {
                EntityUtils.consume(entity);
            } catch (Exception e) {
                logger.error("post http error!", e);
            }
        }
        return null;
    }*/
}